package com.ruoyi.extend.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.db.domain.ApplicationInfo;
import com.ruoyi.db.domain.ChannelInfo;
import com.ruoyi.db.domain.CountInfo;
import com.ruoyi.db.domain.SpecialCostomManagerInfo;
import com.ruoyi.db.mapper.ApplicationInfoMapper;
import com.ruoyi.db.mapper.ChannelInfoMapper;
import com.ruoyi.db.mapper.CountInfoMapper;
import com.ruoyi.db.mapper.SpecialCostomManagerInfoMapper;
import com.ruoyi.db.model.param.BatchEditChannelParam;
import com.ruoyi.db.model.param.ChannelInfoParam;
import com.ruoyi.extend.service.IChannelInfoService;
import com.ruoyi.market.constant.RedisKeyConstent;
import com.ruoyi.market.constant.SystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 渠道信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-08-04
 */
@Service
@DataSource(DataSourceType.SLAVE)
public class ChannelInfoServiceImpl implements IChannelInfoService 
{
    @Resource
    private ChannelInfoMapper channelInfoMapper;
    @Resource
    private CountInfoMapper countInfoMapper;
    @Resource
    private ApplicationInfoMapper applicationInfoMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Resource
    private SpecialCostomManagerInfoMapper specialCostomManagerInfoMapper;

    /**
     * 查询渠道信息
     * 
     * @param channelCode 渠道信息主键
     * @return 渠道信息
     */
    @Override
    public ChannelInfo selectChannelInfoByChannelCode(String channelCode)
    {
        return channelInfoMapper.selectChannelInfoByChannelCode(channelCode);
    }

    @Override
    public ChannelInfo selectChannelInfoByChannelName(String channelName)
    {
        return channelInfoMapper.selectChannelInfoByChannelName(channelName);
    }

    /**
     * 查询渠道信息列表
     * 
     * @param channelInfo 渠道信息
     * @return 渠道信息
     */
    @Override
    public List<ChannelInfo> selectChannelInfoList(ChannelInfo channelInfo)
    {
        return channelInfoMapper.selectChannelInfoList(channelInfo);
    }

    /**
     * 查询渠道信息列表
     *
     * @return 渠道信息
     */
    @Override
    public List<Map<String, Object>> selectChannelInfoListMap(ChannelInfoParam channelInfoParam)
    {
        return channelInfoMapper.selectChannelInfoListMap(channelInfoParam);
    }

    /**
     * 新增渠道信息
     * 
     * @param channelInfoParam 渠道信息
     * @return 结果
     */
    @Override
    public int insertChannelInfo(ChannelInfoParam channelInfoParam)
    {
        // 不包含产品信息处理
        if (StringUtils.isNotEmpty(channelInfoParam.getNotIncludeProduct())){
            String[] split = channelInfoParam.getNotIncludeProduct().split(",");
            JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(split));
            channelInfoParam.setNotIncludeProduct(jsonArray.toJSONString());
        }

        // 不包含请求来源处理
        if (StringUtils.isNotEmpty(channelInfoParam.getNotIncludeSource())){
            String[] split = channelInfoParam.getNotIncludeSource().split(",");
            JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(split));
            channelInfoParam.setNotIncludeSource(jsonArray.toJSONString());
        }

        // 应用推广链接处理
        ApplicationInfo applicationInfo = applicationInfoMapper.getEntityByAppType(channelInfoParam.getAppType());
        String extUrl = StrUtil.format(SystemConstant.CHANNEL_EXT_URL_FORMAT, applicationInfo.getExtUrl(), channelInfoParam.getChannelCode());
        channelInfoParam.setExtUrl(extUrl);
        channelInfoParam.setAppName(applicationInfo.getAppName());
        channelInfoParam.setAppType(applicationInfo.getAppType());

        // 联登类型处理
        if (ObjectUtil.equal(channelInfoParam.getChargeType(), Integer.valueOf("3"))){
            channelInfoParam.setUnionFlag(Integer.valueOf("1"));
        }else{
            channelInfoParam.setUnionFlag(Integer.valueOf("0"));
        }

        SysUser sysUser = ShiroUtils.getSysUser();
        channelInfoParam.setOwnerId(String.valueOf(sysUser.getUserId()));
        channelInfoParam.setOwnerName(sysUser.getUserName());

        channelInfoParam.setCreateTime(DateUtils.getNowDate());
        return channelInfoMapper.insertChannelInfo(channelInfoParam);
    }

    public static void main(String[] args) {
        System.out.println(RandomUtil.randomStringUpper(6));
    }

    /**
     * 修改渠道信息
     * 
     * @param channelInfoParam 渠道信息
     * @return 结果
     */
    @Override
    public int updateChannelInfo(ChannelInfoParam channelInfoParam)
    {
        if (StringUtils.isNotEmpty(channelInfoParam.getNotIncludeProduct())){
            String[] split = channelInfoParam.getNotIncludeProduct().split(",");
            JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(split));
            channelInfoParam.setNotIncludeProduct(jsonArray.toJSONString());
        }

        if (StringUtils.isNotEmpty(channelInfoParam.getNotIncludeSource())){
            String[] split = channelInfoParam.getNotIncludeSource().split(",");
            JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(split));
            channelInfoParam.setNotIncludeSource(jsonArray.toJSONString());
        }

        if (ObjectUtil.equal(channelInfoParam.getChargeType(), Integer.valueOf("3"))){
            channelInfoParam.setUnionFlag(Integer.valueOf("1"));
        }else if(ObjectUtil.equal(channelInfoParam.getChargeType(), Integer.valueOf("1")) ||
                ObjectUtil.equal(channelInfoParam.getChargeType(), Integer.valueOf("2"))){
            channelInfoParam.setUnionFlag(Integer.valueOf("0"));
        }

        CountInfo updatEntity = new CountInfo();
        updatEntity.setDateInfo(LocalDate.now().toString());
        updatEntity.setChannelCode(channelInfoParam.getChannelCode());
        updatEntity.setUpdateTime(new Date());

        if (ObjectUtil.isNotEmpty(channelInfoParam.getChannelRate())){
            updatEntity.setChannelRate(channelInfoParam.getChannelRate());
            countInfoMapper.updateCountInfo(updatEntity);
        }

        if (ObjectUtil.isNotEmpty(channelInfoParam.getChannelType())){
            updatEntity.setChannelType(channelInfoParam.getChannelType());
            countInfoMapper.updateCountInfo(updatEntity);
        }

        if (ObjectUtil.isNotEmpty(channelInfoParam.getAppType())){
            //修改 渠道信息的扩展链接
            ApplicationInfo applicationInfo = applicationInfoMapper.getEntityByAppType(channelInfoParam.getAppType());
            String extUrl = StrUtil.format(SystemConstant.CHANNEL_EXT_URL_FORMAT, applicationInfo.getExtUrl(), channelInfoParam.getChannelCode());
            channelInfoParam.setExtUrl(extUrl);
            channelInfoParam.setAppName(applicationInfo.getAppName());
        }

        ChannelInfo channelInfo = this.channelInfoMapper.selectChannelInfoByChannelCode(channelInfoParam.getChannelCode());
        if (ObjectUtil.isNotEmpty(channelInfoParam.getOwnerId()) && ObjectUtil.isNotEmpty(channelInfo) &&
                !StrUtil.equals(channelInfo.getOwnerId(), channelInfoParam.getOwnerId())){
            updatEntity.setDateInfo(null);
            SpecialCostomManagerInfo specialCostomManagerInfo = specialCostomManagerInfoMapper.selectSpecialCostomManagerInfoByUserId(Long.valueOf(channelInfoParam.getOwnerId()));
            updatEntity.setOwnerId(String.valueOf(specialCostomManagerInfo.getUserId()));
            updatEntity.setOwnerName(specialCostomManagerInfo.getUsername());
            countInfoMapper.updateCountInfo(updatEntity);
        }

        channelInfoParam.setUpdateTime(DateUtils.getNowDate());
        int i = channelInfoMapper.updateChannelInfo(channelInfoParam);

        String redisKey = RedisKeyConstent.CHANNEL_INFO_KEY+channelInfoParam.getChannelCode();
        if (i>0){
            redisTemplate.delete(redisKey);
        }
        return i;
    }

    /**
     * 批量删除渠道信息
     * 
     * @param ids 需要删除的渠道信息主键
     * @return 结果
     */
    @Override
    public int deleteChannelInfoByIds(String ids)
    {

        ChannelInfoParam channelInfoParam = new ChannelInfoParam();
        channelInfoParam.setChannelCode(ids);
        channelInfoParam.setDelFlag(1);
        int i = channelInfoMapper.updateChannelInfo(channelInfoParam);

        String redisKey = RedisKeyConstent.CHANNEL_INFO_KEY+channelInfoParam.getChannelCode();
        if (i>0){
            redisTemplate.delete(redisKey);
        }
        return i;
    }

    /**
     * 删除渠道信息信息
     * 
     * @param id 渠道信息主键
     * @return 结果
     */
    @Override
    public int deleteChannelInfoById(Long id)
    {
        return channelInfoMapper.deleteChannelInfoById(id);
    }

    @Override
    public List<Map<String, String>> selectSimpleMapInfo(ChannelInfoParam channelInfoParam) {
        return channelInfoMapper.selectSimpleMapInfo(channelInfoParam);
    }


}
